<template>
    <!-- 主体区域 -->
    <section id="app">
        <!-- 输入框 -->
        <TodoHeader @add="handleAdd"></TodoHeader>
        <!-- 列表区域 -->
        <TodoMain :list="list" @del="handleDel"></TodoMain>
        <!-- 统计和清空 -->
        <TodoFooter :list="list" @clear="handleDelAll"></TodoFooter>
    </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";
export default {
    data() {
        return {
            list: (JSON.parse(localStorage.getItem('list')) || []).length > 0
                ? JSON.parse(localStorage.getItem('list'))
                : [
                    { id: 1, name: '打篮球' },
                    { id: 2, name: '逛街' },
                    { id: 3, name: '看电影' }
                ]
        }
    },
    components: {
        TodoHeader,
        TodoMain,
        TodoFooter
    },
    methods: {
        handleAdd(todoName) {
            this.list.push({ id: +new Date(), name: todoName })
        },
        handleDel(id) {
            this.list = this.list.filter(item => item.id !== id)
        },
        handleDelAll() {
            this.list = []
        }
    },
    watch: {
        list: {
            deep: true,
            handler(newValue) {
                localStorage.setItem('list', JSON.stringify(newValue))
            }
        }
    }
}
</script>

<style></style>
